<?php
/**
 * Created by PhpStorm.
 * User: Jacky
 * Date: 2015/11/16
 * Time: 14:06
 * 用户
 */

namespace Admin\Model;

use Base\Model\BaseModel;

class UserModel extends BaseModel
{
    protected $tableName = 'user';

    protected $_validate = array(
        array('name', 'require', '用户名必须填写', 1, '', 1),
//        array('phone', 'require', '手机号必须填写'),
//        array('user_group_id', 'require', '用户角色无效'),
        array('name', '', '用户名已经存在', self::VALUE_VALIDATE, 'unique', 1),
        array('phone', '', '手机号已经存在', self::VALUE_VALIDATE, 'unique', 1),
        array('email', '', '邮箱已经存在', self::VALUE_VALIDATE, 'unique', 1),
        array('email', 'email', '邮箱格式不正确！',self::VALUE_VALIDATE, '', self::MODEL_BOTH),
        array('phone','11','手机号长度不对！', self::VALUE_VALIDATE, 'length', self::MODEL_BOTH),
        array('phone','/^(0|86|17951)?(13[0-9]|15[012356789]|18[0-9]|14[57])[0-9]{8}$/','手机号不合法！',self::VALUE_VALIDATE),
        array('pwd', 'require', '密码不能为空！', 1, '', 1),
        array('pwd','6,16','密码长度必须在6-16位之间！',self::VALUE_VALIDATE,'length', self::MODEL_BOTH),
//        array('pwd', 'pwd2', '两次密码不一致', self::VALUE_VALIDATE, 'confirm', self::MODEL_UPDATE)
    );

    protected $_auto = array(
        array('status', '1'),
        array('create_time', 'time', self::MODEL_INSERT, 'function'),
        array('last_time', 'time', self::MODEL_BOTH, 'function'),
        array('pwd', '', self::MODEL_UPDATE, 'ignore'),   //编辑排除密码 为空则忽略
        array('pwd', 'md5', self::MODEL_BOTH, 'function')
    );
    /**
     * @param $user_id
     * @return mixed
     * 获取用户
     */
    public function getUser($user_id){
        $data = $this->relation(true)->where(array(
            'status' => 1,
            'id' => $user_id,
        ))->find();
        return $data;
    }

    public function login($name, $pwd)
    {
        $data = $this->relation(true)->where(array(
            'name' => $name,
            'pwd' => md5($pwd),
            'status' => 1,
        ))->find();
        if (!empty($data)) {
            $token = md5($data['id'] . time());
            $this->where('status=1 and id=%d', array($data['id']))->setField('token', $token);
            return $data;
        } else {
            return false;
        }
    }
}